package com.grad.webstudy.service.impl;

import com.grad.webstudy.constants.RedisConstants;
import com.grad.webstudy.context.UserContext;
import com.grad.webstudy.dao.CourseChapterDao;
import com.grad.webstudy.enums.ExceptionEnums;
import com.grad.webstudy.exceptions.CustomException;
import com.grad.webstudy.model.CourseChapter;
import com.grad.webstudy.model.CourseDetail;
import com.grad.webstudy.model.History;
import com.grad.webstudy.model.User;
import com.grad.webstudy.service.CourseChapterService;
import com.grad.webstudy.service.CourseDetailService;
import com.grad.webstudy.service.HistoryService;
import com.grad.webstudy.utils.RedisUtil;
import com.grad.webstudy.vo.CourseChapterVo;
import com.grad.webstudy.vo.CourseDetailVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * @Description:
 * @Author: zjf
 * @Date: 2020/2/9 10:23.
 */

@Service
@Transactional
public class CourseChapterServiceImpl implements CourseChapterService {

    @Autowired
    private RedisUtil redisUtil;


    @Autowired
    private CourseChapterDao courseChapterDao;


    @Autowired
    private CourseDetailService courseDetailService;

    @Autowired
    private HistoryService historyService;


    @Override
    public int addChapter(CourseChapter courseChapter) {
        courseChapterDao.insert(courseChapter);
        redisUtil.delByPrefix(RedisConstants.REDIS_COURSECHAPTER_KEY_PREFIX);
        return courseChapter.getId();
    }

    @Override
    public boolean addChapters(List<CourseChapter> chapters) {
        redisUtil.delByPrefix(RedisConstants.REDIS_COURSECHAPTER_KEY_PREFIX);

        return courseChapterDao.insertChapters(chapters) > 0;
    }

    @Override
    public boolean deleteChapters(String ids) {

        List<String> deleteIds = Arrays.asList(ids.split(","));
        if (deleteIds.size() <= 0) {
            throw new CustomException(ExceptionEnums.CUSTOM_ERROR.getCode(), "参数ids[" + ids + "]传入错误");
        }
        courseDetailService.deleteByChapterIds(ids);
        redisUtil.delByPrefix(RedisConstants.REDIS_COURSECHAPTER_KEY_PREFIX);

        return courseChapterDao.deleteChaptersByIds(deleteIds) == deleteIds.size();
    }

    @Override
    public boolean deleteChaptersByCourseId(Integer courseId) {
        redisUtil.delByPrefix(RedisConstants.REDIS_COURSECHAPTER_KEY_PREFIX);

        return courseChapterDao.deleteChapterByCourseId(courseId) > 0;
    }

    @Override
    public boolean updateChapter(CourseChapter courseChapter) {
        redisUtil.delByPrefix(RedisConstants.REDIS_COURSECHAPTER_KEY_PREFIX);

        return courseChapterDao.updateChapter(courseChapter) > 0;
    }

    @Override
    public List<CourseChapterVo> queryChaptersByCourseId(Integer courseId) {

        List<CourseChapterVo> result;
//        String key = RedisConstants.REDIS_COURSECHAPTER_KEY_PREFIX + "queryAll" + courseId;
//        if (redisUtil.hasKey(key)) {
//            result = (List<CourseChapterVo>) redisUtil.get(key);
//        } else {
            result = chapterConvertToVo(courseChapterDao.queryAllGroupByCourseId(courseId));
//            redisUtil.set(key, result);
//        }
        return result;
    }

    @Override
    public CourseChapter queryChapterById(Integer courseChapterId) {
        return courseChapterDao.selectByPrimaryKey(courseChapterId);
    }


    private List<CourseChapterVo> chapterConvertToVo(List<CourseChapter> chapters) {
        List<CourseChapterVo> result = new ArrayList<>(chapters.size());
        int index = 1;
        for (CourseChapter chapter : chapters) {
            result.add(new CourseChapterVo.Builder()
                    .setName("第" + index + "章:" + chapter.getChapterName())
                    .setLabel("第" + index + "章:" + chapter.getChapterName())
                    .setId(chapter.getId())
                    .setChapterId(chapter.getId())
                    .setCourseId(chapter.getCourseId())
                    .setSequence(chapter.getSequence())
                    .setChildren(detailConvertToVo(courseDetailService.queryByChapterId(chapter.getId()), index))
                    .build());
            index++;
        }
        return result;
    }

    private List<CourseDetailVo> detailConvertToVo(List<CourseDetail> courseDetails, Integer index) {

        int detailIndex = 1;
        List<CourseDetailVo> result = new ArrayList<>(courseDetails.size());

//        User loginUser = UserContext.getLoginUser();

        for (CourseDetail courseDetail : courseDetails) {
            CourseDetailVo courseDetailVo = new CourseDetailVo.Builder()
                    .setId(courseDetail.getId())
                    .setDetailId(courseDetail.getId())
                    .setChapterId(courseDetail.getChapterId())
                    .setVideoLength(courseDetail.getVideoLength())
                    .setVideoPath(courseDetail.getVideoPath())
                    .setSequence(courseDetail.getSequence())
                    .setName(index + "-" + detailIndex + ":" + courseDetail.getName())
                    .setLabel(index + "-" + detailIndex + ":" + courseDetail.getName())
                    .build();
//            if (Objects.nonNull(loginUser)){
//                Integer userId = loginUser.getId();
//                History history = historyService.queryCourseDetailHistory(courseDetail.getId(),userId);
////                courseDetailVo.setProgress(history.getProgress());
//            }
            result.add(courseDetailVo);
            detailIndex++;
        }
        return result;
    }
}
